<template>
  <div>
    <layout-box one="商品管理" two="分类参数">
      <!-- 给组件绑定的所有的事件 都是自定义事件 -->
      <!-- native让自定义事件以原生事件的方式触发 -->
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            :options="catelist"
            :props="cateProps"
            v-model="selectedCateKeys"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态属性" name="many">
          <el-button :disabled="isDisabled" @click="addDialogVisible=true" type="primary">添加属性</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border="" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(i,scope.row)"
                >{{ item }}</el-tag>
                <!-- input与button的切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- =============================================================== -->
        <el-tab-pane label="静态参数" name="only">
          <el-button @click="addDialogVisible=true" :disabled="isDisabled" type="primary">添加参数</el-button>
          <!-- 静态参数的表格 -->
          <el-table :data="onlyTableData" border="" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(i,scope.row)"
                >{{ item }}</el-tag>
                <!-- input与button的切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数的对话框 -->
      <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%">
        <!-- 添加参数的对话框 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数的对话框 -->
      <el-dialog :title="'修改' + titleText" :visible.sync="eidtDialogVisible" width="50%">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </layout-box>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      catelist: [],
      // 级联选择框的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
      // tabs的默认选中项
      activeName: "many",
      //动态参数的列表数据
      manyTableData: [],
      // 静态参数的列表数据
      onlyTableData: [],
      addDialogVisible: false,
      eidtDialogVisible: false,
      addFormRules: {
        attr_name: [{ required: true, message: "必填", trigger: "blur" }]
      },
      editFormRules: {
        attr_name: [{ required: true, message: "必填", trigger: "blur" }]
      },
      // 添加弹窗中表单的数据
      addForm: {
        attr_name: ""
      },
      editForm: {
        attr_name: ""
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！");
      }

      this.catelist = res.data;

      // console.log(this.catelist);
    },
    // 级联选择器切换值
    handleChange() {
      // 限制选择范围为 只能选择三级
      this.getParamsList();
    },
    // 点击切换tabs
    handleClick() {
      // console.log(this.activeName);
      this.getParamsList();
    },
    // 获取参数列表
    async getParamsList() {
      // 设置级联选择器可选范围
      if (this.selectedCateKeys.length < 3) {
        this.selectedCateKeys = [];
        this.manyTableData = []
        this.onlyTableData = []
        return false;
      }
      // console.log(this.selectedCateKeys);
      // 根据所选分类的Id，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败！");
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      // 把返回的数据中的成员里 attr_vals 改成数组\
      // 建议修改res.data 修改完了 再赋值给this.xxxx
      // 而不要直接改this.xxx上的属性为数组
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
      // console.log(manyTableData)
    },
    // 添加参数方法
    async addParams() {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        }
      );
      if (res.meta.status != 201) {
        return this.$message.error("添加参数失败");
      }
      this.addDialogVisible = false;
      this.getParamsList();
    },
    // 修改参数方法
    async editParams() {
      console.log(123);
      // console.log(attrInfo);
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      );

      if (res.meta.status != 200) {
        return this.$message.error("修改失败");
      }
      this.eidtDialogVisible = false;
      this.getParamsList();
    },
    //展示修改弹窗
    async showEdit(attrInfo) {
      this.eidtDialogVisible = true;
      this.editForm = attrInfo;
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果 row.inputValue不为空 则发送请求新增一条参数的可选项
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    deleteTag(i, row) {
      // 移除数组中的对应项
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
    // 封装的用于修改可选项的方法
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("修改参数项失败！");
      }

      this.$message.success("修改参数项成功！");
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  },
  computed: {
    isDisabled: function() {
      if (this.selectedCateKeys.length != 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId: function() {
      return this.selectedCateKeys[this.selectedCateKeys.length - 1];
    },
    titleText: function() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>